<?php

namespace App\Models\Member;

use Auth;
use App\Models\BaseModel;

class CodeRecord extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'user_id', 'phone', 'code',
        'type', 'expire_at', 'created_at', 'updated_at'
    ];

    /**
     * 生成验证码记录
     *
     * @param storeId 店铺id
     * @param code 随机验证码 
     * @param phone 操作对象 手机或者邮箱号码
     * @param handleType 操作类型
     * @return array
     */
    public function makeCodeRecord($code, $storeId, $phone, $handleType)
    {
        $codeRecord = $this->where('store_id',$storeId)
                      ->where('type', $handleType)
                      ->where('phone', $phone)
                      ->first();

        $user = Auth::user();
        $userId = empty($user) ? 0 : $user->id;
        $expireAt = date("Y-m-d H:i:s", strtotime( "+5 minutes"));
        // 无目标数据
        if (empty($codeRecord)) {
            $this->create([
                'store_id' => $storeId,
                'user_id' => $userId,
                'phone' => $phone,
                'code' => $code,
                'type' => $handleType,
                'expire_at' => $expireAt
            ]);
            return ['res' => true];
        }

        $repeatTimestamp =date('Y-m-d H:i:s', strtotime("-60 seconds"));
        if ($codeRecord->updated_at > $repeatTimestamp)
            return ['res'=>false, 'info'=>'请一分钟之后再试'];

        $codeRecord->user_id = $userId;
        $codeRecord->code = $code;
        $codeRecord->expire_at = $expireAt;
        $codeRecord->save();
        return ['res' => true];
    }

}
